package com.qianniu.napi.admin.web;

import akka.actor.ActorRef;
import akka.actor.Props;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.base.Strings;
import com.qianniu.napi.admin.entity.*;
import com.qianniu.napi.admin.entity.penum.GtypeEnum;
import com.qianniu.napi.admin.entity.penum.Qtype;
import com.qianniu.napi.admin.service.*;
import com.qianniu.napi.admin.service.akka.AkkaServer;
import com.qianniu.napi.admin.service.akka.StoreActor;
import com.qianniu.napi.common.config.Constants;
import com.qianniu.napi.common.util.ObjectUtil;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 优惠券模板
 * </p>
 *
 * @author chenxuebin
 * @since 2018-07-07
 */
@Controller
public class CouponTplController {

    private static final Logger logger = LoggerFactory.getLogger(CouponTplController.class);

    @Autowired
    private IRedisService redisService;
    @Autowired
    private ICouponTplService coupontplService;
    @Autowired
    private ICoupontplExtService coupontplExtService;
    @Autowired
    private IMerchantConfigService merchantConfigService;
    @Autowired
    private IStoreService storeService;
    @Autowired
    private IGoodsService goodsService;

    @RequiresPermissions("admin:user:view")
    @RequestMapping("admin/coupontpl/index")
    public String index(Model model) {

        if(ObjectUtil.getUserType()>=36){//营销类功能才有此权限
            List<Store> mchs = storeService.selectList(new EntityWrapper<Store>()
                    .setSqlSelect("id,name").eq("mpid",ObjectUtil.getMpid()));
            model.addAttribute("mchs", mchs);
        }
        MerchantApp mapp = redisService.getMApp(ObjectUtil.getMpid());

        model.addAttribute("multisid", mapp.getVersion()==3||mapp.getVersion()==4);
        model.addAttribute("isAdmin", ObjectUtil.getIsAdmin());
        model.addAttribute("utype", ObjectUtil.getUserType());

        CoupontplExt coupontplExt = coupontplExtService.selectOne(new EntityWrapper<CoupontplExt>()
                .eq("mpid",ObjectUtil.getMpid()));

        List<Config> quantypes = new ArrayList<Config>();
        Config config = null;
        if(coupontplExt==null){
            config = new Config();
            config.setName("代金券");
            config.setType("1");
            quantypes.add(config);

            config = new Config();
            config.setName("满减券");
            config.setType("2");
            quantypes.add(config);

            config = new Config();
            config.setName("折扣券");
            config.setType("3");
            quantypes.add(config);

        }else{

            if(coupontplExt.getDaijin()!=null&&coupontplExt.getDaijin().intValue()==1){
                config = new Config();
                config.setName("代金券");
                config.setType(Qtype.daijin.getVal().toString());
                quantypes.add(config);
            }
            if(coupontplExt.getManjian()!=null && coupontplExt.getManjian().intValue()==1){
                config = new Config();
                config.setName("满减券");
                config.setType(Qtype.manjian.getVal().toString());
                quantypes.add(config);
            }
            if(coupontplExt.getZhekou()!=null && coupontplExt.getZhekou().intValue()==1){
                config = new Config();
                config.setName("折扣券");
                config.setType(Qtype.zhekou.getVal().toString());
                quantypes.add(config);
            }
            if(coupontplExt.getJiaxi()!=null && coupontplExt.getJiaxi().intValue()==1){
                config = new Config();
                config.setName("加息券");
                config.setType(Qtype.jiaxi.getVal().toString());
                quantypes.add(config);
            }
            if(coupontplExt.getTimes()!=null && coupontplExt.getTimes().intValue()==1){
                config = new Config();
                config.setName("次卡");
                config.setType(Qtype.times.getVal().toString());
                quantypes.add(config);
            }
            if(coupontplExt.getWeek()!=null && coupontplExt.getWeek().intValue()==1){
                config = new Config();
                config.setName("周卡");
                config.setType(Qtype.week.getVal().toString());
                quantypes.add(config);
            }
            if(coupontplExt.getMonth()!=null && coupontplExt.getMonth().intValue()==1){
                config = new Config();
                config.setName("月卡");
                config.setType(Qtype.month.getVal().toString());
                quantypes.add(config);
            }
            if(coupontplExt.getSeason()!=null && coupontplExt.getSeason().intValue()==1){
                config = new Config();
                config.setName("季卡");
                config.setType(Qtype.season.getVal().toString());
                quantypes.add(config);
            }
            if(coupontplExt.getHalfyear()!=null && coupontplExt.getHalfyear().intValue()==1){
                config = new Config();
                config.setName("半年卡");
                config.setType(Qtype.halfyear.getVal().toString());
                quantypes.add(config);
            }
            if(coupontplExt.getYear()!=null && coupontplExt.getYear().intValue()==1){
                config = new Config();
                config.setName("年卡");
                config.setType(Qtype.year.getVal().toString());
                quantypes.add(config);
            }
            if(coupontplExt.getUnlimit()!=null && coupontplExt.getUnlimit().intValue()==1){
                config = new Config();
                config.setName("畅游卡");
                config.setType(Qtype.unlimit.getVal().toString());
                quantypes.add(config);
            }
        }

        model.addAttribute("quantypes", quantypes);

        List<Store> stores = storeService.selectList(new EntityWrapper<Store>()
                .setSqlSelect("id,name")
                .eq("state",1)
                .eq("status",2)
                .eq("mpid",ObjectUtil.getMpid()));
        List<Store> allstores = new ArrayList<Store>();
        Store pt = new Store();
        pt.setId(0l);
        pt.setName("平台");
        allstores.add(pt);
        allstores.addAll(stores);
        model.addAttribute("stores", allstores);

        return "admin/coupontpl";
    }

    @RequiresPermissions("admin:user:view")
    @RequestMapping("/admin/coupontpl/list")
    @ResponseBody
    public Page<CouponTpl> alist(@RequestParam(value = "offset", required = false) Integer offset,
                                 @RequestParam(value = "status", required = false) Integer status,
                                 @RequestParam(value = "search", required = false) String search,
                                 @RequestParam(value = "limit", required = false) Integer limit) {
        Wrapper<CouponTpl> wrapper = new EntityWrapper<CouponTpl>();
        int utype = ObjectUtil.getUserType();
        if (utype < 39)
            wrapper.eq("mpid", ObjectUtil.getMpid());
        else if (utype < 99)
            wrapper.eq("mid", ObjectUtil.getMid());

//        wrapper.eq("state", 1);
        if (status != 99) wrapper.eq("type", status);
        if (!Strings.isNullOrEmpty(search))
            wrapper.like("name", search);

        wrapper.orderBy("id", false);
        Page<CouponTpl> page = coupontplService.selectPage(new Page<CouponTpl>(offset / limit+1, limit), wrapper);
        return page;
    }

    @RequestMapping("/admin/coupontpl/add")
    public String add(@Valid CouponTpl bean, Model model) {
        logger.info(">>>>>CouponTpl getStarttime=" + bean.getStarttime());
        logger.info(">>>>>CouponTpl getEndtime=" + bean.getEndtime());

        if (bean.getState() == null) bean.setState(0);
        bean.setCreatetime(new Date());
        bean.setState(1);//默认启用
        bean.setIsHome(-1);//默认非首页券
        if(bean.getType().intValue()>=10){
            bean.setIsRepeat(1);
            bean.setTotal(-1);// 总数量，-1 无限制
            bean.setIsForever(-1);// 是否无限期
            bean.setIsHome(-1);// 是否首页券
            bean.setIsSystem(-1);// 是否系统券
            bean.setUse(0);// 使用量
            if(bean.getType().intValue()>10)
                bean.setCost(new BigDecimal(-1));//
            else bean.setUsemin(new BigDecimal(0));
        }

        bean.setMid(ObjectUtil.getMid());
        bean.setMpid(ObjectUtil.getMpid());
        bean.setUid(ObjectUtil.getUid());
        if(bean.getSid()!=null&&bean.getSid()>0){
            Store store = storeService.selectOne(new EntityWrapper<Store>().setSqlSelect("id,name")
                    .eq("id",bean.getSid()));
            bean.setSname(store.getName());
        }
        bean.insert();

        if(ObjectUtil.getUserType()>=36){//营销类功能才有此权限
            List<Store> mchs = storeService.selectList(new EntityWrapper<Store>().setSqlSelect("id,name").eq("mpid",ObjectUtil.getMpid()));
            model.addAttribute("mchs", mchs);
        }

        MerchantApp mapp = redisService.getMApp(ObjectUtil.getMpid());
        model.addAttribute("multisid", mapp.getVersion()==3||mapp.getVersion()==4);
        model.addAttribute("isAdmin", ObjectUtil.getIsAdmin());
        model.addAttribute("utype", ObjectUtil.getUserType());

        return "redirect:index";
    }

    @RequestMapping("/admin/coupontpl/addQuangoods")
    public String addQuangoods(@Valid Goods bean) {
        logger.info(">>>>>CouponTpl addQuangoods=" + JSON.toJSONString(bean));
        CouponTpl tpl = coupontplService.selectById(bean.getTplid());
        if(tpl==null){
            return "redirect:index";
        }
        bean.setGtype(GtypeEnum.xu.getVal());//到店
        bean.setState(1);
        bean.setType(-2);//券类商品
        bean.setStores(-1);//库存
        bean.setCreatetime(new Date());
        bean.setMid(tpl.getMid());
        bean.setMpid(tpl.getMpid());
        bean.setSid(tpl.getSid());
        String[] photos = bean.getPhotos().split(";");
        if(photos.length>0)bean.setPic(photos[0]);

        if(bean.getId()==null)bean.insert();
        else bean.updateById();

        AkkaServer.system.actorOf(Props.create(StoreActor.class))
                .tell(Constants.AKKA_MSG_GOODS_MODIFY + "@" + bean.getId(), ActorRef.noSender());

        return "redirect:index";
    }

    @RequestMapping("/admin/coupontpl/getQuanGoods")
    @ResponseBody
    public Jinfo getQuanGoods(Long tplid) {
        logger.info(">>>>>getQuanGoods tplid=" + tplid);
        Jinfo jinfo = new Jinfo();
        Goods goods = goodsService.selectOne(new EntityWrapper<Goods>().eq("tplid",tplid));
        jinfo.setInfo(goods);

        return jinfo;
    }

    @RequestMapping("/admin/coupontpl/getCouponTplById")
    @ResponseBody
    public CouponTpl getCouponTplById(long id) {

        CouponTpl coupontpl = coupontplService.selectById(id);
        return coupontpl;
    }

    @RequestMapping("/admin/coupontpl/deleteOne")
    @ResponseBody
    public int deleteOne(long id) {
        boolean isSucc = coupontplService.deleteById(id);
        return isSucc ? 1 : 0;
    }

    @RequestMapping("/admin/coupontpl/changeState")
    @ResponseBody
    public String changeState(long id, int state) {
        CouponTpl bean = new CouponTpl();
        bean.setId(id);
        bean.setState(state);
        bean.setModifytime(new Date());
        bean.setModifier(ObjectUtil.getUid());
        coupontplService.updateById(bean);
        return "success";
    }

    @RequestMapping("/admin/coupontpl/changeHomeState")
    @ResponseBody
    public String changeHomeState(long id, int state) {
        CouponTpl bean = new CouponTpl();
        bean.setId(id);
        bean.setIsHome(state);
        bean.setModifytime(new Date());
        bean.setModifier(ObjectUtil.getUid());
        coupontplService.updateById(bean);

        MerchantConfig mc = merchantConfigService.selectOne(
                new EntityWrapper<MerchantConfig>()
                .eq("mpid", ObjectUtil.getMpid()));
        mc.setVersion(mc.getVersion() + 1);
        mc.insertOrUpdate();
        return "success";
    }

    @RequestMapping("/admin/coupontpl/modify")
    public String update(CouponTpl bean) {
        bean.setModifytime(new Date());
        bean.setModifier(ObjectUtil.getUid());
        bean.setModifier(ObjectUtil.getMid());
        boolean isSuccc = coupontplService.updateById(bean);
        if (isSuccc) {
            return "redirect:index";
        }
        return "error";
    }

}
